import {
  reqAssignRoleByUser,
  reqDeleteCheckedUser,
  reqDeleteUser,
  reqRoleData,
  reqAddOrUpdateUser,
  reqUserPageInfo,
} from "@/api/user";
import { Message } from "element-ui";

const state = {
  userList: [],
  roleList: [],
};

const mutations = {
  SET_USERLIST(state, userList) {
    state.userList = userList;
  },
  SET_ROLELIST(state, roleList) {
    state.roleList = roleList;
  },
};

const actions = {
  // 获取用户列表
  async getUserList({ commit }, { page, limit, username }) {
    try {
      let result = await reqUserPageInfo(page, limit, username);
      if (result.code === 20000) {
        commit("SET_USERLIST", result.data);
        return result.data.total;
      } else {
        Message.error("获取用户列表失败");
      }
    } catch (error) {
      return Promise.reject(new Error("请求获取用户列表失败"));
    }
  },
  // 添加或修改用户
  async addOrUpdate({ commit }, userInfo) {
    try {
      await reqAddOrUpdateUser(userInfo);
      Message.success(userInfo.id ? "修改用户成功" : "添加用户成功");
      return "ok";
    } catch (error) {
      return Promise.reject(new Error("请求获取用户列表失败"));
    }
  },
  // 删除用户
  async removeUser({ commit }, id) {
    try {
      await reqDeleteUser(id);
      Message.success("删除用户成功");
      return "ok";
    } catch (error) {
      return Promise.reject(new Error("删除用户失败"));
    }
  },
  // 批量删除用户
  async removeCheckedUser({ commit }, idList) {
    // console.log("api中的idList是", idList);
    try {
      // console.log("user中的idList是", idList);
      await reqDeleteCheckedUser(idList);
      Message.success("批量删除用户成功");
      return "ok";
    } catch (error) {
      return Promise.reject(new Error("批量删除用户失败"));
    }
  },

  // 根据用户获取用户角色数据
  async getUserRoles({ commit }, id) {
    try {
      let result = await reqRoleData(id);
      // console.log(result);
      commit("SET_ROLELIST", result.data);
      return result.data;
    } catch (error) {
      return Promise.reject(new Error("获取用户角色失败"));
    }
  },

  // 根据用户分配角色
  async assignRoles({ commit }, { userId, roleIdList }) {
    console.log(userId, roleIdList);
    try {
      await reqAssignRoleByUser(userId, roleIdList);
      Message.success("分配角色成功");
      return "ok";
    } catch (error) {
      return Promise.reject(new Error("请求分配角色失败"));
    }
  },
};

const getters = {};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
